package com.zhenwo.zlb.sso;

import java.net.URISyntaxException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.Date;
import java.util.Map;

import javax.net.ssl.X509TrustManager;

import com.alibaba.fastjson.JSON;

import com.moralbank.utils.MD5;
import org.apache.http.client.utils.URIBuilder;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.ssl.SSLSocketFactoryBuilder;

public class Sso {
    static final String ssoAuthUrl = "https://ddyh.yy.gov.cn/v2/sso/ssoauth/";
    static final String ssoInfoUrl = "https://ddyh.yy.gov.cn/v2/sso/organduser/";

    static X509TrustManager tm = new X509TrustManager() {

        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {

        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {

        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }

    };

    // 登录sso，换取userid用于下一步认证，出错时，如果是业务错误，返回SsoError，其他均为内部错误
    public static SsoUserInfo Login(String token)
            throws SsoError, KeyManagementException, NoSuchAlgorithmException, URISyntaxException {
        Validation info = query(ssoAuthUrl, "ticketValidation", Validation.class, Collections.singletonMap("st", token));
        return query(ssoInfoUrl, "getUserInfoById", SsoUserInfo.class,
                Collections.singletonMap("userid", info.getUserid()));
        //return query(ssoInfoUrl, "getUserInfoById", SsoUserInfo.class,
        //        Collections.singletonMap("userid", token));
    }

    private static <T extends SsoResult> T query(String base, String method, Class<T> class1, Map<String, String> args)
            throws SsoError, URISyntaxException, KeyManagementException, NoSuchAlgorithmException {
        String timeStr = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        URIBuilder builder = new URIBuilder(base);
        builder.addParameter("method", method);
        builder.addParameter("servicecode", "ddyh");
        builder.addParameter("time", timeStr);
        builder.addParameter("sign", sign(timeStr));
        builder.addParameter("datatype", "json");

        for (Map.Entry<String, String> entry : args.entrySet()) {
            builder.addParameter(entry.getKey(), entry.getValue());
        }

        HttpRequest get = HttpUtil.createGet(builder.build().toString()).timeout(1000 * 15);

        get.setSSLSocketFactory(SSLSocketFactoryBuilder.create().setTrustManagers(tm).build());

        String body = get.execute().body();
        T val = JSON.parseObject(body, class1);

        if (val.IsError()) {
            throw val.getError();
        }

        return val;
    }

    private static String sign(String timeStr) {
        return MD5.GetMD5Code("xxxx", "pwd", timeStr);
    }

    public static void main(String[] args) {
        URIBuilder builder;
        try {
            SsoUserInfo login = Login("xxxx");
            System.out.println(login.toString());
        } catch (URISyntaxException e) {
            e.printStackTrace();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        } catch (SsoError e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

    }
}